import { Breadcrumb, Layout, Button, Badge, Avatar, message } from "antd";
import React, { useEffect, useState } from "react";
const { Header, Content, Footer, Sider } = Layout;
// 引入菜单
import MyMenu from "../../components/MyMenu";
import { Outlet } from "react-router-dom";
import { useNavigate } from "react-router-dom";
import { useTranslation, Trans } from "react-i18next";
import {
  listApplications,
  listWarehouseProducts,
  listWarehouses,
} from "../../api/ckgl";
import RemindTag from "../../components/RemindTag";
import { BellOutlined } from "@ant-design/icons";

const Home: React.FC = () => {
  const [count, setCount] = useState<number>(0);
  // 声明
  const [collapsed, setCollapsed] = useState(false);
  const [breadcrumb, setBreadcrumb] = useState<string[]>([]);
  const { t, i18n } = useTranslation();
  const [applicationToal, setApplicationsTotal] = useState<number>(0);
  const navigate = useNavigate(); // Access the navigate function using useNavigate

  const handleBreadcrumbChange = (newBreadcrumb: string[]) => {
    setBreadcrumb(newBreadcrumb);
    console.log("状态存储", breadcrumb);
  };

  const handleClick = () => {
    navigate("/login");
    localStorage.removeItem("react-jwt-token");
    localStorage.removeItem("token");
    localStorage.removeItem("role_code");
    localStorage.removeItem("user_id");
  };

  const getListReturnApplications = (page: number) => {
    let applicant_id, administrator_id;
    if (["admin", "m-admin"].includes(localStorage?.role_code)) {
      administrator_id = localStorage?.user_id;
    } else {
      applicant_id = localStorage?.user_id;
    }
    listApplications({
      page: page,
      size: 20,
      administrator_id,
      applicant_id,
      //     int32 applicant_id = 3; // 领物人员（user_id）登陆，传applicant_id
      // int32 administrator_id = 4; // 物资管理员或超管登陆（user_id）, 传administrator_id
    }).then((res: any) => {
      if (res?.code !== 0) {
        message.error(res.msg);
        return;
      }
      const { applications, total } = res.data;

      setApplicationsTotal(total);
    });
  };

  // const getListWarehouses = () => {
  //   // 调用 listSuppliers API，并处理响应
  //   listWarehouses({
  //     page: 1,
  //     size: 300,
  //   }).then((res: any) => {
  //     if (res?.code !== 0) {
  //       message.error(res.msg);
  //       return;
  //     }
  //     const { warehouses, total } = res.data;
  //     let _count = 1;
  //     warehouses.forEach((el: any) => {
  //       if (el?.reminder) {
  //         setRemind(true);
  //         _count++;
  //       }
  //     });
  //     setCount(_count);
  //   });
  // };

  const getListWarehouseProducts = () => {
    // 调用 listWarehouseProducts API，并处理响应
    listWarehouseProducts({
      page: 1,
      size: 300,
    }).then((res: any) => {
      if (res?.code !== 0) {
        message.error(res.msg);
        return;
      }
      const { warehouse_products, total } = res.data;
      console.log("warehouse_products", warehouse_products);
      let _count = 1;
      warehouse_products.forEach((el: any) => {
        if (el?.reminder) {
          _count++;
        }
      });
      setCount(_count);
    });
  };

  useEffect(() => {
    getListReturnApplications(1);
    // ["admin", "m-admin"].includes(localStorage?.role_code) &&
    //   getListWarehouseProducts();
  }, []);

  return (
    <Layout style={{ minHeight: "100vh" }}>
      {/* 侧边栏 */}
      <Sider
        collapsible
        collapsed={collapsed}
        onCollapse={(value) => setCollapsed(value)}
      >
        <div className="logo">
          <h1
            style={{
              fontSize: "24px",
              color: "white",
              textAlign: "center",
              display: "flex",
              alignItems: "center",
            }}
          >
            {collapsed ? "" : "高校物资仓储管理系统"}
          </h1>
        </div>

        {/* 菜单 */}
        <MyMenu onBreadcrumbChange={handleBreadcrumbChange} />
      </Sider>
      <Layout className="site-layout">
        {/* 内容区域头部 */}
        <Header className="site-layout-background" style={{ padding: "1 px" }}>
          <div
            style={{
              float: "right",
              marginBottom: "51px",
            }}
          >
            {["admin", "m-admin", "picker"].includes(
              localStorage?.role_code
            ) ? (
              <Badge count={applicationToal}>
                <Avatar
                  shape="square"
                  size="large"
                  onClick={() => {
                    navigate("/list-applications");
                  }}
                  style={{ verticalAlign: "middle" }}
                >
                  {localStorage?.username?.[0] || "默"}
                </Avatar>
              </Badge>
            ) : (
              <>
                <Avatar
                  shape="square"
                  size="large"
                  style={{ verticalAlign: "middle" }}
                >
                  {localStorage?.username?.[0] || "默"}
                </Avatar>
              </>
            )}
            {localStorage?.username || ""}
            <Button
              type="primary"
              onClick={handleClick}
              style={{ marginLeft: 8 }}
            >
              退出登录
            </Button>
            {/* <Button
              style={{ marginLeft: "5px" }}
              type="primary"
              onClick={() =>
                i18n.changeLanguage(i18n.language == "en" ? "zh" : "en")
              }
            >
              {i18n.language == "en" ? "中文" : "English"} <SwapOutlined />
            </Button> */}
          </div>
          <p>
            欢迎来到高校物资仓储管理系统
            {/* {["admin", "m-admin"].includes(localStorage?.role_code) && (
              <>
                {"    "}
                <RemindTag
                  remind={!!count}
                  text={"仓库物品闽值标识"}
                  onClick={() => navigate("/list-warehouse-products")}
                />
                <Badge count={count} offset={[10, 0]}>
                  <BellOutlined
                    style={{ fontSize: "24px" }}
                    onClick={() => navigate("/list-warehouse-products")}
                  />
                </Badge>
              </>
            )} */}
          </p>
          {/* <p>{t("language")}</p> */}
          {/* <Breadcrumb style={{ margin: ' 0' }}>
            <Breadcrumb.Item>User</Breadcrumb.Item>
            <Breadcrumb.Item>Bill</Breadcrumb.Item>
          </Breadcrumb> */}

          <Breadcrumb style={{ margin: " 0" }}>
            {breadcrumb.map((item, index) => (
              <Breadcrumb.Item key={index}>{item}</Breadcrumb.Item>
            ))}
          </Breadcrumb>
        </Header>
        {/* 内容区 */}
        <Content
          style={{
            margin: " 16px 16px 0 16px",
            background: "white",
            padding: "16px",
          }}
        >
          <Outlet />
        </Content>
        {/* 底部 */}
        <Footer style={{ textAlign: "center", padding: 0, lineHeight: "50px" }}>
          高校物资仓储管理系统
        </Footer>
      </Layout>
    </Layout>
  );
};

export default Home;
